package com.gr.blog.mean.action;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gr.blog.dept.model.DeptModel;
import com.gr.blog.dept.service.DeptService;
import com.gr.blog.mean.model.MenuModel;
import com.gr.blog.mean.service.MeanService;
import com.gr.blog.user.model.UserModel;
import com.gr.blog.utils.CollectionsUtil;
import com.gr.blog.utils.CommonUtils;
import com.gr.blog.utils.PageHelperUtils;
import com.gr.blog.utils.ResponseUtils;

/**
 * 菜单管理的action
 * @author:gbp
 * 2017年12月25日 上午11:32:07
 */
@Controller
public class MeanAction {

	private static final Logger logger = Logger.getLogger(MeanAction.class);
	
	@Autowired
	@Qualifier(value="meanService")
	private MeanService meanService;
	
	@Autowired
	@Qualifier("deptService")
	private DeptService deptService;
	
	/**
	 * 部门权限管理界面点击权限分配时，展示【已存在】部门和菜单关系的数据
	 * @author:巩斌鹏
	 * 2018年6月3日 下午2:53:12
	 * @return
	 * Map<String,Object>
	 */
	@RequestMapping("meanAction/showLeftManuDate")
	public @ResponseBody Map<String,Object> showLeftManuDate(HttpServletRequest request,int page,int start,int limit){
		Map<String,Object> deptMap = new HashMap<String,Object>();
		String dgId = request.getParameter("dgId");//dgid实际上是部门的id
		deptMap.put("dgId", dgId);
		deptMap.put("start", start);
		deptMap.put("limit", limit);
		List<MenuModel> deptList = meanService.showLeftManuDate(deptMap);
		deptMap.put("root", deptList);
		if (CollectionsUtil.isListNotEmpty(deptList)){
			deptMap.put("total", deptList.size());
		} 
		deptMap.put("total", "");
		logger.error("[左边的查询数据]:"+deptMap);
		return deptMap;
	}
	/**
	 * 部门权限管理界面点击权限分配时，展示【不存在】部门和菜单关系的数据
	 * @author:巩斌鹏
	 * 2018年6月3日 下午2:53:22
	 * @return
	 * Map<String,Object>
	 */
	@RequestMapping("meanAction/showRightManuDate")
	public @ResponseBody Map<String,Object> showRightManuDate(HttpServletRequest request,int page,int start,int limit){
		Map<String,Object> deptMap = new HashMap<String,Object>();
		String dgId = request.getParameter("dgId");//dgid实际上是部门的id
		deptMap.put("dgId", dgId);
		deptMap.put("start", start);
		deptMap.put("limit", limit);
		List<MenuModel> deptList = meanService.showRightManuDate(deptMap);
		deptMap.put("root", deptList);
		if (CollectionsUtil.isListNotEmpty(deptList)){
			deptMap.put("total", deptList.size());
		} 
		deptMap.put("total", "");
		logger.error("[右边的查询数据]:"+deptMap);
		return deptMap;
	}
	
	
	
	
	/**
	 * 受页面进去之后加载所有的菜单
	 * @author:gbp
	 * @param request
	 * @return
	 * 2018年1月23日 上午11:39:05
	 * @throws IOException 
	 */
	@RequestMapping("meanAction/showAllTree")
	public @ResponseBody List<Map<String,Object>> showAllTree(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		Map<String,Object> menuMap = new HashMap<>();
		String node = request.getParameter("node");
		String mCode = request.getParameter("mCode");
		if (CommonUtils.isNotEmpty(mCode)){
			int mcodelength = mCode.length();
			menuMap.put("mCode", mCode);
			menuMap.put("mcodelength", mcodelength*2);
		}
		menuMap.put("node", node);
		
		UserModel user = (UserModel) request.getSession().getAttribute("userModel");
		response.setContentType("text/html;charset=utf-8");
		if (null != user && "superadmin".equals(user.getUsername()) && "root".equals(node)){
			List<Map<String,Object>> superModelMap = meanService.showSuperAllTree(menuMap);
			return superModelMap;
		}else if (null != user && !"root".equals(node)){
			List<Map<String,Object>> superModelMap = meanService.showAllTree(menuMap);
			return superModelMap;
		} else {
			List<DeptModel> deptSessionList = user.getDeptList();
			if (CollectionsUtil.isListNotEmpty(deptSessionList)){
				if (null != node && "root".equals(node)) {
					List<DeptModel> deptList =deptService.getDeptInfoByUserName(user.getUid());
					String allDeptId = "";
					if (CollectionsUtil.isListNotEmpty(deptList)) {
						for (DeptModel dm :deptList) {
							int deptid = dm.getDgId();
							allDeptId +=deptid+",";
						}
						logger.error("[showAllTree查询得到的部门id]："+allDeptId);
						if (CommonUtils.isNotEmpty(allDeptId)) {
							menuMap.put("deptId", Arrays.asList(allDeptId.split(",")));
						} else {
							response.getWriter().print("{\"success\": true,\"flag\":\"true\",\"msg\":\"您还没有任何权限，请联系管理员赋权之后在来！！！\" }");
							return null;
						}
					}
					logger.error("[查询菜单树时，最后的数据map]:"+menuMap);
					List<Map<String,Object>> superModelMap = meanService.showAllTree(menuMap);
					return superModelMap;
				} else {
					List<Map<String,Object>> superModelMap = meanService.showAllTree(menuMap);
					return superModelMap;
				}
			} else {
				response.getWriter().print("{\"success\": true,\"flag\":\"true\",\"msg\":\"您还没有任何权限，请联系管理员赋权之后在来！！！\" }");
				return null;
			}
		}
	}
	
	/**
	 * 菜单管理页面显示菜单信息的方法
	 * @author:gbp
	 * @param request
	 * @param page
	 * @param start
	 * @param limit
	 * @return
	 * 2018年1月23日 上午11:42:00
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("meanAction/showALLTreeMenu")
	public @ResponseBody PageHelperUtils<MenuModel> showALLTreeMenu(HttpServletRequest request,
			int page,int start,int limit) throws UnsupportedEncodingException{
		String manuName = request.getParameter("menuName");
		if (CommonUtils.isNotEmpty(manuName)) {
			manuName = new String(manuName.getBytes("iso8859-1"),"utf-8");
		}
		PageHelperUtils<MenuModel> menuList = meanService.showALLTreeMenu(manuName,page,start,limit);
		return menuList;
		
	}
	
	/**
	 * 新增菜单是 显示父类节点的方法
	 * @author:gbp
	 * @return
	 * 2018年1月23日 下午3:35:36
	 */
	@RequestMapping("meanAction/findFeatherMenu")
	public @ResponseBody List<Map<String,Object>> findFeatherMenu(){
		List<Map<String,Object>> menuList = meanService.findFeatherMenu();
		return menuList;
		
	}
	
	@RequestMapping("meanAction/addMenuInfoToDb")
	public void addMenuInfoToDb(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String, String[]> menuMap = request.getParameterMap();
		Map<String,Object> addmap = new HashMap<String,Object>();
		addmap = CollectionsUtil.MapArrayToMapObject(menuMap, addmap);
		
		UserModel userModel = (UserModel)request.getSession().getAttribute("userModel");
		addmap.put("operate", userModel.getUsername());
		int result = meanService.addMenuInfoToDb(addmap);
		ResponseUtils.returnResult(response, result);
	}
	
	/**
	 * 查询出所有的对应菜单与部门的关系
	 * @author:巩斌鹏
	 * 2018年6月3日 上午9:05:55
	 * @return
	 * Map<String,Object>
	 */
	public Map<String,Object> getRepeatMenuIdInfo(){
		Map<String,Object> resultMap = new HashMap<>();
		TreeSet<Integer> ts=new TreeSet<>();
		List<Map<String,Object>> menuAndDeptList = meanService.findMenuAndDept();
		if (CollectionsUtil.isListNotEmpty(menuAndDeptList)){
			String tt = "";
			for (Map<String,Object> map : menuAndDeptList) {
				int menuid = (int) map.get("menuid");
				ts.add(menuid);
				if (ts.contains(menuid)) {
					String value = (String) map.get("dgName");
					String resultTT = (String) resultMap.get(menuid+"");
					if (CommonUtils.isNotEmpty(resultTT)) {
						tt = resultTT+","+ value;
					} else {
						tt = value;
					}
				} 
				resultMap.put(menuid+"", tt);
				tt = "";
			}
			logger.error("[查询出所有的对应菜单与部门的关系]:"+resultMap);
			return (Map<String, Object>)resultMap;
		}
		return null;
	}
	/**
	 * 【菜单管理界面】 根据菜单id删除菜单信息
	 * @author:巩斌鹏
	 * 2018年6月5日 下午2:26:31
	 * void
	 * @throws IOException 
	 */
	@RequestMapping("meanAction/deleteMeunInfoByid")
	public @ResponseBody void deleteMeunInfoByid(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String menuId = request.getParameter("menuId");
		//先查是不是父类节点id，
		List<Integer> mgIdList = meanService.findMenuAndDeptLinkByMenuId(menuId);
		response.setContentType("text/html;charset=utf-8");
		if (CollectionsUtil.isListNotEmpty(mgIdList)) {
			response.getWriter().print("{\"success\": true,\"flag\":\"false\", \"msg\":\"该菜单下存在部门信息，暂时无法删除！！！\"}");
			return;
		} 
		int deleteNum = meanService.deleteMenuInfoByMenuId(menuId);
		ResponseUtils.returnDeleteResult(response, deleteNum);
	}
}
